package com.yc.backstage.security.handler;

import cn.hutool.json.JSONUtil;
import com.yc.common.res.ResultClass;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Classname JwtAccessDeniedHandler
 * @Description 当用户访问了不属于自己权限的访问路径的时候得函数 AccessDeniedHandler：当用户访问了不属于自己权限的访问路径的时候得触发得异常处理器
 * @Version 1.0.0
 * @Date 2022/7/26 15:40
 * @Created by Mikechen
 */
@Component
public class AccessDeniedHandler implements org.springframework.security.web.access.AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        ServletOutputStream outputStream = response.getOutputStream();
        ResultClass result = ResultClass.fail(401, accessDeniedException.getMessage());
        outputStream.write(JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
